using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Services.Client;
using System.Linq;
using OrbitOne.CRMLyncInfoDashboard.CRM.OData;
using OrbitOne.CRMLyncInfoDashboard.CRM.OrganizationData;

namespace OrbitOne.CRMLyncInfoDashboard.CRM
{
    [Export(typeof(ILyncDashboardSavedQueryProvider))]
    public class LyncDashboardSavedQueryProvider : ILyncDashboardSavedQueryProvider
    {
        private List<Tuple<EntityModelTypes, string>> m_configurationMapping = new List<Tuple<EntityModelTypes, string>>
                                                                                   {
                                                                                       new Tuple<EntityModelTypes, string>(EntityModelTypes.AccountModel, "LyncDashboardAccountView"),
                                                                                       new Tuple<EntityModelTypes, string>(EntityModelTypes.ContactModel, "LyncDashboardContactView"),
                                                                                       new Tuple<EntityModelTypes, string>(EntityModelTypes.LeadModel, "LyncDashboardLeadView")
                                                                                   };

        public void GetByName(EntityModelTypes entityModelType, Action<IAsyncResult> onConfigurationLoaded, EntityData model)
        {
            var firstOrDefault = m_configurationMapping.FirstOrDefault(cm => cm.Item1 == entityModelType);
            if (firstOrDefault == null) return;
            var configName = firstOrDefault.Item2;
        
            var ctx = new LabContext();
            var query = (DataServiceQuery<SavedQuery>)((DataServiceQuery<SavedQuery>)ctx.GetEntitySet<SavedQuery>())
                                                          .Where(config => config.Name == configName);

            var userState = new UserState(model, query);

            query.BeginExecute(new AsyncCallback(onConfigurationLoaded), userState);
        }
    }
}